package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.common.utils.DateUtil;
import com.tanhua.commons.template.AipFaceTemplate;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.commons.template.OssTemplate;
import com.tanhua.commons.template.SmsTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.db.UserStatus;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserStatusApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.DateTimeException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserService {
    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Reference
    private UserStatusApi userStatusApi;

    @Value("tanhua.secret")
    private String secret;
    /**
     * 向Redis中存储验证码值时，key的前缀
     */
    private String smsPrefix = "CODE_";
    private String tokenPrefix = "TOKEN_";

    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @return
     */
    public ResponseEntity login(String mobile) {
//        String code = smsTemplate.sendSms(mobile);
        String code = "123456";
        //把验证码存储到Redis里，有效期5分钟
        redisTemplate.opsForValue().set(smsPrefix + mobile, code, Duration.ofMinutes(5));
        //构造返回值
        return ResponseEntity.ok(null);
    }

    /**
     * @param mobile 手机号
     * @param code   用户输入的验证码
     * @return
     */
    public ResponseEntity loginVerification(String mobile, String code) {
        //从redis中获取验证码
        String value = redisTemplate.opsForValue().get(smsPrefix + mobile);
        //验证码失效或不正确，直接返回响应
        if (value == null || !value.equals(code)) {
            return ResponseEntity.status(500).body(ErrorResult.smsInvalid());
        }
        //验证码校验完成，清除缓存的验证码值
        redisTemplate.delete(smsPrefix + mobile);
        //根据手机号查询用户
        User user = userApi.findByMobile(mobile);
        //如果手机号不存在，则自动注册
        boolean isNew = false;
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            //保存用户，返回id
            long id = userApi.save(user);
            user.setId(id);

            //把用户注册到环信
            huanXinTemplate.register(user.getId().toString(), "123456");
            isNew = true;
        }

        //查询用户信息表
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //校验用户状态

        if (userInfo.getUserStatus().equals("2")) {
            UserStatus userStatus = userStatusApi.findByUserId(user.getId().intValue());
            Integer freezingRange = userStatus.getFreezingRange();
            if (freezingRange == 1) {
                return ResponseEntity.status(503).body("该账户已冻结");
            }
        }

        // ====使用RocketMQ推送消息，记录日志   start====
        Map<String, Object> message = new HashMap<>();
        message.put("userId", user.getId());
        message.put("type", isNew ? "0102" : "0101");
        message.put("date", new DateTime().toString("yyyy-MM-dd"));
        rocketMQTemplate.convertAndSend("tanhua-log", message);
        log.info("使用RocketMQ发送消息：{}", message);
        // ====使用RocketMQ推送消息，记录日志   end====
        //生成令牌
        String token = JwtUtils.createToken(mobile, user.getId(), secret);
        //把user对象存储到redis里
        redisTemplate.opsForValue().set(tokenPrefix + token, JSON.toJSONString(user),
                Duration.ofHours(1));
        //构造返回值
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);

        return ResponseEntity.ok(result);
    }

    public ResponseEntity saveUserInfo(UserInfo userInfo) {
        //获取当前用户
        User user = UserHolder.getUser();
        //给userInfo补全数据
        Long userId = user.getId();
        userInfo.setId(userId);
        //保存用户信息
        userInfoApi.save(userInfo);
        //返回结果
        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveAvatar(MultipartFile headPhoto) throws IOException {
        //获取当前用户
        User user = UserHolder.getUser();

        //人脸检测
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceDetectFailed());
        }

        //把头像上传到阿里云
        String path = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //更新到数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(path);

        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }
}
